<template>
  <div>
    <basic-dialog :visible="show"
                  minWidth="700px"
                  title="推送设置"
                  :isShowClose="false"
                  :isFullScreen="false"
                  :isShowBasicFooter="true"
                  @close="$emit('close'); onReset()"
                  :loading="isSubmitting"
                  @submit="submit">
      <q-card-section class="margin-b-10">
        <div class="margin-b-20">
          <strong>推送方式:</strong>
          <q-checkbox
            v-for="item in selectionList"
            v-model="sendWay"
            :key="item.value"
            :val="item.value"
            class="q-mr-sm"
            :label="item.label"/>
        </div>
        <q-table
          :data="tableData"
          :columns="columns"
          row-key="id"
          hide-bottom
          class="stick-last-col"
          separator="cell"
          no-data-label="暂无数据"
          color="primary"
        >
          <template v-slot:body-cell-rule="{ row }">
            <q-td>
              <div class="flex no-wrap items-center">
                <span>{{ ruleName.desc }}</span>
                <q-input
                  dense
                  border
                  outlined
                  v-if="!ruleName.isRule && row.set"
                  ref="rule"
                  class="q-ml-sm q-mr-sm"
                  v-model.number.trim="row.threshold"
                  :maxlength="4"
                  style="width:100px;height:44px"
                  @blur="checkData(row)"
                  @keyup.enter="checkData(row)"
                />
                <span style="color: red" v-else>{{ row.threshold }}</span>
                <span>{{ ruleName.unit }}</span>
              </div>
            </q-td>
          </template>
          <template v-slot:body-cell-group="{ row }">
            <q-td @click="addRole(row)">
              <div class="role-container" v-if="!row.msgGroups || row.msgGroups.length===0">添加角色</div>
              <div class="ellipsis" v-else>{{getMsgGroupNames(row.msgGroups)}} <q-tooltip>{{getMsgGroupNames(row.msgGroups)}}</q-tooltip></div>
            </q-td>
          </template>
          <template v-slot:body-cell-operations="props">
            <q-td class="operations" style="width: 100px">
              <q-btn flat dense round color="primary" icon="iconfont icontubiao-12" :disable="!ruleName.unit" @click="editRule(props.row)">
                <q-tooltip>编辑</q-tooltip>
              </q-btn>
              <q-btn flat dense round color="primary" icon="iconfont icontubiao-16" @click="deleteRule(props.row)">
                <q-tooltip>删除</q-tooltip>
              </q-btn>
            </q-td>
          </template>
        </q-table>
        <div class="add-wrapper" v-if="showAddIcon" @click="addRule">
          <q-icon name="iconfont icontubiao-39" class="margin-r-10" />添加
        </div>
      </q-card-section>
    </basic-dialog>

    <RolesSelect :show="rolesShow"
                 @close="rolesShow=false"
                 :sourceData="sourceData"
                 :haveSelected="haveSelected"
                 @selectSuccess="selectRoleSuccess"/>
  </div>
</template>
<script>
import _ from 'lodash'
import MsgList from './msg-list.js'
import RolesSelect from './roles-select'
import { mapGetters } from 'vuex'
import { delMessage, putMessage } from '../../../../boot/factory/msg-list'
const { sendWayList } = new MsgList()
export default {
  name: 'msg-detail-dialog',
  components: {
    RolesSelect
  },
  props: {
    show: Boolean,
    setData: Object,
    roleList: Array
  },
  data () {
    return {
      isSubmitting: false,
      sendWay: [], // !按产品需求,推送方式暂时固定为 0 - APP
      setMsgData: {},
      // 要修改的触发条件
      rule: '',
      ruleName: {
        desc: '',
        unit: '',
        isRule: true
      },
      rightList: [],
      ruleWhite: ['TPM_OVERAGE_INFO'], // 支持一位小数白名单
      // 选中的角色
      groupIds: [],
      roles: [], // 角色列表
      selectionList: [], // 推送方式
      tableData: [],
      columns: [
        { name: 'rule', label: '触发条件', align: 'left', field: 'rule' },
        { name: 'group', label: '接收角色', align: 'left', field: 'group' },
        { name: 'operations', label: '操作', align: 'left', field: 'operations' }
      ],
      rolesShow: false,
      sourceData: null,
      editRow: null
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    haveSelected () {
      if (!this.editRow) {
        return []
      }
      return _.cloneDeep(this.editRow).msgGroups
    },
    showAddIcon () {
      if (this.ruleName.isRule) {
        return this.tableData.length < 1
      }
      return this.tableData.length < 5
    }
  },
  watch: {
    show (val) {
      if (val) {
        this.initData()
      }
    },
    setData: {
      immediate: true,
      deep: true,
      handler (val) {
        if (val) {
          this.sendWay = val.sendWays
          this.tableData = val.rules.map(item => {
            return {
              set: false,
              ...item
            }
          })
        }
      }
    }
  },
  mounted () {
  },
  methods: {
    submit () {
      if (this.sendWay.length === 0) {
        this.$message.warning('请至少选择一种推送方式')
        return
      }
      const check = this.tableData.every(item => {
        if (item.msgGroups.length === 0) {
          this.$message.warning('所选角色不能为空')
        }
        return this.checkData(item) && item.msgGroups.length > 0
      })
      if (!check) return
      const data = _.cloneDeep(this.tableData)
      data.forEach(item => {
        delete item.set
        if (item.id.startsWith('__')) {
          item.id = ''
        }
        item.msgGroupId = item.msgGroups.map(item => item.id)
        delete item.set
        delete item.msgGroups
      })
      const params = {
        sendWays: this.sendWay,
        rules: data
      }
      this.isSubmitting = true
      putMessage(this.setMsgData.id, params).then(() => {
        this.$message.success('操作成功')
        this.$emit('close')
      }).finally(() => {
        this.isSubmitting = false
      })
      // const params = {
      //   business: this.setMsgData.business,
      //   id: this.setMsgData.id,
      //   sendWay: this.sendWay,
      //   groupIds: this.groupIds,
      //   userId: this.userInfo.user_id,
      //   rule: this.rule
      // }
      // this.isSubmitting = true
      // Promise.all([putMessageUpdate(params), putMessageBind(params)]).then(res => {
      //   this.isSubmitting = false
      //   this.$message.success('操作成功')
      //   this.$emit('close')
      // }).catch(err => {
      //   this.isSubmitting = false
      //   console.log(err)
      // })
    },
    checkData (row) {
      const val = row.threshold
      if (this.ruleName.isRule) {
        return true
      } else if (val === '') {
        this.$message.warning('不能为空')
      } else if (val <= 0) {
        row.set = true
        this.$message.warning('不能小于或等于0')
      } else if (this.ruleName.unit === '%' && val > 100) {
        row.set = true
        this.$message.warning('不能超过100')
      } else if (this.ruleName.unit === '%' && val < 0) {
        row.set = true
        this.$message.warning('不能小于0')
      } else if (!this.ruleName.unit) {
        return true
      } else if (this.ruleName.check && !/^[1-9]\d*$/.test(val)) {
        this.$message.warning('只能输入整数')
        row.set = true
      } else {
        row.set = false
        return true
      }
      return false
    },
    editRule (row) {
      row.set = true
    },
    addRule () {
      // 制造伪id，防止表格循环报错
      const id = '__' + Math.random().toString(36).substr(2, 9)
      const rowData = { id: id, threshold: 0, set: false, msgGroups: [] }
      if (!this.ruleName.unit) {
        rowData.threshold = ''
      }
      this.tableData.push(rowData)
    },
    deleteRule (row) {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>确认删除该条信息吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(() => {
        if (!row.id.startsWith('__')) {
          delMessage(row.id).then(() => {
            const index = row.__index
            this.tableData.splice(index, 1)
          })
        } else {
          const index = row.__index
          this.tableData.splice(index, 1)
        }
      })
    },
    setRules () {
      let member = [val => val !== '' || '不能为空!', val => val > 0 || '不能为 0 !', val => val < 99999 || '数量过大']
      this.ruleWhite.includes(this.setData.business) ? member.push(val => /^\d+(\.\d)?$/.test(val) || '最多一位小数') : member.push(val => /^\d+$/.test(val) || '只能填写整数')
      return member
    },
    // 初始化显示
    initData () {
      const member = _.cloneDeep(this.roleList)
      this.roles = member[0].value === 'all' ? _.tail(member) : member
      this.selectionList = sendWayList
      this.setMsgData = _.cloneDeep(this.setData)
      if (this.setMsgData.business) {
        const { desc, unit, isRule, check } = this.setMsgData.ruleName
        this.$set(this.ruleName, 'desc', desc)
        this.$set(this.ruleName, 'unit', unit)
        this.$set(this.ruleName, 'isRule', isRule)
        this.$set(this.ruleName, 'check', check)
        this.rightList = this.setData.roles
        this.rule = this.setData.rule
      }
    },
    // clear search
    onReset () {
      this.groupIds = []
      this.selection = []
    },
    // 提示
    // 注意提示
    noticeMessage (message) {
      this.$message.warning(message)
    },
    addRole (row) {
      this.rolesShow = true
      this.editRow = row
      this.sourceData = _.cloneDeep(this.roles)
    },
    // 更新选中的角色
    selectRoleSuccess (data) {
      this.editRow.msgGroups = data
      this.rolesShow = false
    },
    // 获取选中的角色名称
    getMsgGroupNames (group) {
      let name = ''
      group.forEach((item, index) => {
        name += item.name
        if (index !== group.length - 1) name += '、'
      })
      return name
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/ .q-table__container{
  border-radius: 6px 6px 0 0;
}
.add-wrapper{
  width: 100%;
  height: 48px;
  background: #F3F3F3;
  border-radius: 0px 0px 6px 6px;
  font-size: 14px;
  font-weight: 500;
  color: #5F77FD;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.role-container{
  width: 96px;
  height: 32px;
  background: #FFFFFF;
  border: 1px dashed #5F77FD;
  border-radius: 6px;
  text-align: center;
  line-height: 32px;
  color: #5f77fd;
  cursor: pointer;
  user-select: none
}
.operations{
  background: #FFFFFF;
}
</style>
